<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能情绪交互平台</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/material-design-icons/3.0.1/iconfont/material-icons.min.css" rel="stylesheet">
    <style>
        /* 基础重置 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Microsoft YaHei', '宋体', sans-serif;
        }

        /* 海浪背景 */
        body {
            min-height: 100vh;
            background: linear-gradient(90deg, #87CEEB, #F0FFFF, #87CEEB);
            position: relative;
            overflow-x: hidden;
            background-size: 400% 400%;
            animation: seaWave 20s ease infinite;
        }

        @keyframes seaWave {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }

        /* 界面容器 */
        .main-container {
            position: relative;
            z-index: 1;
            padding: 0.8rem;
            max-width: 1200px;
            margin: 0 auto;
        }

        /* 情绪显示区 */
        .emotion-panel {
            background: rgba(255, 255, 255, 0.95);
            width: 120px;
            margin: 0.5rem auto;
            padding: 0.8rem;
            border-radius: 12px;
            box-shadow: 0 2px 6px rgba(0,0,0,0.08);
            text-align: center;
            backdrop-filter: blur(8px);
            font-size: 0.9rem;
        }

        .emotion-icon {
            font-size: 2.8rem;
            transition: transform 0.3s ease;
        }

        /* 对话容器 */
        .chat-section {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 1rem;
            margin-top: 1rem;
        }

        .chat-box {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 12px;
            padding: 1rem;
            height: 250px;
            overflow-y: auto;
            box-shadow: 0 2px 6px rgba(0,0,0,0.08);
            backdrop-filter: blur(8px);
        }

        .chat-box h3 {
            color: #2c3e50;
            margin-bottom: 0.8rem;
            font-size: 1rem;
            position: sticky;
            top: 0;
            background: rgba(255, 255, 255, 0.9);
            padding: 5px 0;
            z-index: 1;
        }

        /* 数据展示区域样式 */
        .data-section {
            display: grid;
            grid-template-columns: repeat(3, 1fr); /* 保持三列布局 */
            gap: 1rem;
            margin-top: 1rem;
        }

        .data-card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 12px;
            padding: 1rem;
            box-shadow: 0 2px 6px rgba(0,0,0,0.08);
            backdrop-filter: blur(8px);
            height: 400px;
            overflow-y: auto;
        }

        .data-header {
            display: flex;
            align-items: center;
            margin-bottom: 0.8rem;
            color: #2c3e50;
            font-size: 1rem;
            font-weight: bold;
        }

        .data-header i {
            margin-right: 0.4rem;
            font-size: 1.2rem;
        }

        /* 消息气泡 */
        .message {
            max-width: 85%;
            padding: 0.6rem 0.8rem;
            margin: 0.5rem 0;
            border-radius: 8px;
            animation: fadeIn 0.4s ease;
            position: relative;
        }

        .user-message {
            background: #e8f4fc;
            margin-left: auto;
        }

        .ai-message {
            background: #f0f0f0;
            margin-right: auto;
        }

        .timestamp {
            font-size: 0.65rem;
            color: #666;
            margin-top: 0.2rem;
        }

        /* 功能按钮 */
        .record-btn {
            position: fixed;
            bottom: 1rem;
            right: 1rem;
            width: 48px;
            height: 48px;
            background: #ff4081;
            border: none;
            border-radius: 50%;
            color: white;
            cursor: pointer;
            box-shadow: 0 4px 12px rgba(255,64,129,0.3);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 100;
        }

        .record-btn.active {
            background: #4CAF50;
            transform: scale(1.1);
            box-shadow: 0 6px 16px rgba(76,175,80,0.4);
        }

        .exit-btn {
            position: fixed;
            bottom: 1rem;
            left: 1rem;
            width: 48px;
            height: 48px;
            background: #42CEEB;
            border: none;
            border-radius: 50%;
            color: white;
            cursor: pointer;
            box-shadow: 0 4px 12px rgba(135,206,235,0.3);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 100;
        }

        /* 动画 */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .chat-section, .data-section {
                grid-template-columns: 1fr;
            }
            
            .chat-box {
                height: 200px;
            }
            
            .data-card {
                height: 300px; /* 移动端适当调整高度 */
            }
        }

        /* 新增样式 */
        .vital-item {
            padding: 0.8rem;
            margin: 0.5rem 0;
            background: #f8f9fa;
            border-radius: 8px;
        }

        .vital-label {
            color: #666;
            font-size: 0.9rem;
            margin-bottom: 0.3rem;
        }

        .vital-value {
            font-size: 1.4rem;
            font-weight: 600;
            color: #2c3e50;
        }

        .vital-progress {
            height: 6px;
            background: #eee;
            border-radius: 3px;
            margin-top: 0.5rem;
            overflow: hidden;
        }

        .progress-bar {
            width: 0;
            height: 100%;
            background: #4CAF50;
            transition: width 0.5s ease, background 0.3s;
        }

        .heartbeat-bar.warning { background: #ff5722; }

        /* 情绪告警条目样式 */
        .alert-item {
            background: #f8f9fa;
            padding: 0.6rem;
            margin: 0.3rem 0;
            border-radius: 6px;
            display: flex;
            align-items: center;
            animation: fadeIn 0.3s ease;
        }

        .alert-item::before {
            content: '🔔';
            margin-right: 0.6rem;
            font-size: 1rem;
        }

        .alert-time {
            color: #666;
            font-size: 0.7rem;
            margin-right: 0.6rem;
            min-width: 90px;
        }

        .alert-emotion {
            font-weight: 500;
            color: #2c3e50;
        }

        /* 不同情绪颜色标识 */
        [data-emotion="高兴"] { border-left: 3px solid #4CAF50; }
        [data-emotion="悲伤"] { border-left: 3px solid #2196F3; }
        [data-emotion="生气"] { border-left: 3px solid #FF5722; }
        [data-emotion="平静"] { border-left: 3px solid #9E9E9E; }
        
        /* 柱状图样式 */
        #emotionChartCanvas {
            width: 100%;
            height: 100%;
            display: block;
        }
    </style>
</head>
<body>
    <div class="main-container">
        <!-- 情绪面板 -->
        <div class="emotion-panel">
            <div class="emotion-icon">😐</div>
            <div style="font-size: 0.75rem; color: #666; margin-top: 0.3rem;">情绪感知</div>
        </div>

        <!-- 对话区域 -->
        <div class="chat-section">
            <div class="chat-box" id="userChat">
                <h3>🗣️ 用户对话</h3>
            </div>
            <div class="chat-box" id="aiChat">
                <h3>🤖 AI回复</h3>
            </div>
        </div>

        <!-- 数据展示区域 -->
        <div class="data-section">
            <!-- 情绪统计 -->
            <div class="data-card">
                <div class="data-header">
                    <i class="material-icons">show_chart</i>
                    情绪次数统计
                </div>
                <canvas id="emotionChartCanvas"></canvas>
            </div>

            <!-- 情绪告警 -->
            <div class="data-card">
                <div class="data-header">
                    <i class="material-icons">notifications</i>
                    情绪告警
                </div>
                <div id="alertList"></div>
            </div>

            <!-- 生命体征 -->
            <div class="data-card">
                <div class="data-header">
                    <i class="material-icons">favorite</i>
                    呼吸心跳监测
                </div>
                <div id="vitalData">
                    <div class="vital-item">
                        <div class="vital-label">呼吸频率</div>
                        <div class="vital-value breath-value">-- 次/分钟</div>
                        <div class="vital-progress">
                            <div class="progress-bar breath-bar"></div>
                        </div>
                    </div>
                    <div class="vital-item">
                        <div class="vital-label">心率</div>
                        <div class="vital-value heartbeat-value">-- 次/分钟</div>
                        <div class="vital-progress">
                            <div class="progress-bar heartbeat-bar"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 功能按钮 -->
    <button class="exit-btn" id="exitBtn">
        <i class="material-icons">exit_to_app</i>
    </button>
    <button class="record-btn" id="recordBtn">
        <i class="material-icons">mic</i>
    </button>

    <script>
        // 聊天容器元素
        const userChat = document.getElementById('userChat');
        const aiChat = document.getElementById('aiChat');

        // 滚动位置跟踪
        let userAutoScroll = true;
        let aiAutoScroll = true;

        userChat.addEventListener('scroll', () => {
            const threshold = 30;
            userAutoScroll = userChat.scrollHeight - userChat.scrollTop <= userChat.clientHeight + threshold;
        });

        aiChat.addEventListener('scroll', () => {
            const threshold = 30;
            aiAutoScroll = aiChat.scrollHeight - aiChat.scrollTop <= aiChat.clientHeight + threshold;
        });

        // 获取消息的函数
        async function fetchMessages() {
            try {
                const response = await fetch('/getMessages');
                if (!response.ok) throw new Error('网络响应异常');
                
                const data = await response.json();
                
                // 分离用户和AI的消息
                const userMessages = data.messages.map(msg => ({
                    text: msg.userText,
                    time: msg.time
                }));
                const aiMessages = data.messages.map(msg => ({
                    text: msg.gptText,
                    time: msg.time
                }));

                updateChatBox(userChat, userMessages, 'user-message');
                updateChatBox(aiChat, aiMessages, 'ai-message');
                updateEmotion(data.messages.slice(-1)[0]?.emotion);

            } catch (error) {
                console.error('获取消息失败:', error);
            }
        }

        // 更新聊天框
        function updateChatBox(container, messages, messageClass) {
            const recentMessages = messages.slice(-20);
            const fragment = document.createDocumentFragment();
            
            recentMessages.forEach(msg => {
                const messageDiv = document.createElement('div');
                messageDiv.className = `message ${messageClass}`;
                messageDiv.innerHTML = `
                    <div class="text">${msg.text}</div>
                    <div class="timestamp">${formatTime(msg.time)}</div>
                `;
                fragment.appendChild(messageDiv);
            });

            const title = container.querySelector('h3');
            container.innerHTML = title.outerHTML;
            container.appendChild(fragment);

            if ((container === userChat && userAutoScroll) || 
                (container === aiChat && aiAutoScroll)) {
                container.scrollTop = container.scrollHeight;
            }
        }

        // 时间格式化
        function formatTime(timestamp) {
            const date = new Date(timestamp);
            return date.toLocaleTimeString([], { 
                hour: '2-digit', 
                minute: '2-digit'
            });
        }

        function updateEmotion(emotion) {
            const emojiMap = {
                生气: '😠',
                厌恶: '😖',
                恐惧: '😨',
                高兴: '😊',
                悲伤: '😢',
                惊讶: '😮',
                平静: '😐'
            };
            document.querySelector('.emotion-icon').textContent = 
                emojiMap[emotion] || '😐';
        }

        // 每6秒获取数据
        setInterval(fetchMessages, 6000);
        fetchMessages();

        // 录音控制
        const recordBtn = document.getElementById('recordBtn');
        let isRecording = false;

        recordBtn.addEventListener('click', async () => {
            isRecording = !isRecording;
            recordBtn.classList.toggle('active');
            
            try {
                const url = isRecording ? '/OpenRcd' : '/CloseRcd';
                const response = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        userId: 'user123',
                        recordingStatus: isRecording
                    })
                });

                if (!response.ok) throw new Error('请求失败');
                console.log(`请求成功：${url}`);
            } catch (error) {
                console.error('请求发送失败:', error);
            }
        });

        // 退出功能
        document.getElementById('exitBtn').addEventListener('click', () => {
            window.location.href = 'index.html';
        });

        // 新增全局变量存储情绪数据
        let emotionAlerts = []; // 存储所有情绪告警数据
        const emotionTypes = ['惊讶', '高兴', '平静', '悲伤', '厌恶', '生气', '恐惧'];

        // 获取情绪记录的函数
        async function fetchEmotionAlerts() {
            try {
                const response = await fetch('/getEmotionAlerts');
                if (!response.ok) throw new Error('获取告警失败');
                const data = await response.json();

                // 存储到全局变量
                emotionAlerts = data.alerts;
                
                const alertList = document.getElementById('alertList');
                alertList.innerHTML = data.alerts
                    .map(alert => `
                        <div class="alert-item" data-emotion="${alert.emotion}">
                            <span class="alert-time">${formatAlertTime(alert.timestamp)}</span>
                            <span class="alert-emotion">情绪变化为 ${alert.emotion}</span>
                        </div>`
                    ).join('');
            } catch (error) {
                console.error('告警更新失败:', error);
            }
        }

        // 统计情绪出现次数
        function countEmotions() {
            const countMap = emotionTypes.reduce((acc, cur) => {
                acc[cur] = 0;
                return acc;
            }, {});

            emotionAlerts.forEach(alert => {
                if (countMap.hasOwnProperty(alert.emotion)) {
                    countMap[alert.emotion]++;
                }
            });

            return countMap;
        }

        // 渲染统计结果
        function renderEmotionStats() {
            const stats = countEmotions();
            const canvas = document.getElementById('emotionChartCanvas');
            if (!canvas) return;
            
            const ctx = canvas.getContext('2d');
            // 设置canvas实际大小
            canvas.width = canvas.clientWidth;
            canvas.height = canvas.clientHeight;
            
            // 清除画布
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // 配置参数
            const padding = {left: 60, right: 30, top: 20, bottom: 60};
            const chartWidth = canvas.width - padding.left - padding.right;
            const chartHeight = canvas.height - padding.top - padding.bottom;
            const maxCount = Math.max(...Object.values(stats)) || 1;
            
            // 绘制坐标轴
            ctx.strokeStyle = '#ccc';
            ctx.lineWidth = 1;
            
            // Y轴
            ctx.beginPath();
            ctx.moveTo(padding.left, padding.top);
            ctx.lineTo(padding.left, padding.top + chartHeight);
            ctx.stroke();
            
            // X轴
            ctx.beginPath();
            ctx.moveTo(padding.left, padding.top + chartHeight);
            ctx.lineTo(padding.left + chartWidth, padding.top + chartHeight);
            ctx.stroke();
            
            // 绘制柱状图
            const barWidth = chartWidth / (emotionTypes.length * 1.5);
            const barSpacing = chartWidth / emotionTypes.length;
            
            emotionTypes.forEach((emotion, index) => {
                const value = stats[emotion];
                const percentage = value / maxCount;
                const barHeight = chartHeight * percentage * 0.9;
                
                // 计算位置
                const x = padding.left + index * barSpacing;
                const y = padding.top + chartHeight - barHeight;
                
                // 设置颜色
                const colors = {
                    '生气': '#FF5722',
                    '悲伤': '#2196F3',
                    '惊讶': '#FFC107',
                    '高兴': '#4CAF50',
                    '平静': '#9E9E9E',
                    '厌恶': '#9C27B0',
                    '恐惧': '#673AB7'
                };
                
                // 绘制柱形
                ctx.fillStyle = colors[emotion] || '#666';
                ctx.fillRect(x, y, barWidth, barHeight);
                
                // 绘制数值标签
                ctx.fillStyle = '#333';
                ctx.font = '12px Microsoft YaHei';
                ctx.textAlign = 'center';
                ctx.fillText(value, x + barWidth/2, y - 5);
                
                // 绘制X轴标签
                ctx.save();
                ctx.translate(x + barWidth/2, padding.top + chartHeight + 20);
                ctx.rotate(-Math.PI/4);
                ctx.textAlign = 'right';
                ctx.fillText(emotion, 0, 0);
                ctx.restore();
            });
        }

        // 时间格式化函数
        function formatAlertTime(timestamp) {
            const date = new Date(timestamp);
            return `${date.getFullYear()}/${date.getMonth()+1}/${date.getDate()} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
        }

        // 获取生命体征数据
        async function fetchVitalData() {
            try {
                const response = await fetch('/getVitalData');
                if (!response.ok) throw new Error('获取生命体征失败');
                const data = await response.json();
                
                // 更新呼吸数据
                document.querySelector('.breath-value').textContent = 
                    `${data.breath} 次/分钟`;
                document.querySelector('.breath-bar').style.width = 
                    `${Math.min(data.breath * 2, 100)}%`;
                
                // 更新心跳数据
                document.querySelector('.heartbeat-value').textContent = 
                    `${data.heartbeat} 次/分钟`;
                const heartbeatBar = document.querySelector('.heartbeat-bar');
                heartbeatBar.style.width = `${Math.min(data.heartbeat, 200)}%`;
                heartbeatBar.classList.toggle('warning', data.heartbeat > 100 || data.heartbeat < 60);
            } catch (error) {
                console.error('生命体征更新失败:', error);
            }
        }

        // 初始化加载数据
        async function init() {
            await fetchEmotionAlerts();
            renderEmotionStats();
            fetchVitalData();
            fetchMessages();
        }

        // 设置定时刷新
        setInterval(init, 5000);
        init();
    </script>
</body>
</html>